import * as Cesium from "cesium";

export class RealTimePathManager {
    constructor() {
        this.pathPrimitives = new Map();
        this.pathPositions = new Map();
        this.positionProperties = new Map(); // 存储SampledPositionProperty引用
        this.maxPoints = 2000;

        // 监听时钟来更新路径
        this.setupClockListener();
    }

    // 注册实体和对应的position property
    registerEntity(entityId, positionProperty) {
        // console.log(`注册实体路径: ${entityId}`);

        // 存储position property引用
        this.positionProperties.set(entityId, positionProperty);

        // 初始化位置数组
        this.pathPositions.set(entityId, []);

        // 创建primitive
        this.createPrimitive(entityId);

        // 监听position property的变化
        this.setupPositionListener(entityId, positionProperty);
    }

    // 创建primitive
    createPrimitive(entityId) {
        const polylineCollection = new Cesium.PolylineCollection();
        this.pathPrimitives.set(entityId, polylineCollection);
        viewer.scene.primitives.add(polylineCollection);

        // 初始空折线
        polylineCollection.add({
            positions: [],
            width: 3.0,
            material: Cesium.Material.fromType('Color', { color: this.getLineColor(entityId) })
        });
    }

    // 监听position property的变化
    setupPositionListener(entityId, positionProperty) {
        let lastUpdateTime = null;

        // 监听definitionChanged事件
        positionProperty.definitionChanged.addEventListener((property, name) => {
            if (name === 'value') {
                // 当有新数据添加时，获取当前时间的位置
                const currentTime = viewer.clock.currentTime;
                const currentPosition = positionProperty.getValue(currentTime);

                if (currentPosition) {
                    this.addPositionToPath(entityId, currentPosition);
                }
            }
        });
    }

    // 通过时钟监听来持续更新路径（备选方案）
    setupClockListener() {
        viewer.clock.onTick.addEventListener(() => {
            const currentTime = viewer.clock.currentTime;

            // 遍历所有已注册的实体，更新路径
            this.positionProperties.forEach((positionProperty, entityId) => {
                const currentPosition = positionProperty.getValue(currentTime);
                if (currentPosition) {
                    this.addPositionToPath(entityId, currentPosition);
                }
            });
        });
    }

    // 添加位置到路径
    addPositionToPath(entityId, newPosition) {
        if (!this.pathPositions.has(entityId)) return;

        const positions = this.pathPositions.get(entityId);
        const polylineCollection = this.pathPrimitives.get(entityId);

        if (!positions || !polylineCollection) return;

        // 克隆新位置
        const clonedPosition = Cesium.Cartesian3.clone(newPosition);

        // 检查是否是第一个点或与上个点不同
        if (positions.length === 0 ||
            !this.isSamePosition(positions[positions.length - 1], clonedPosition)) {

            positions.push(clonedPosition);

            // 限制最大点数
            if (positions.length > this.maxPoints) {
                positions.shift();
            }

            // 更新primitive显示
            this.updatePrimitiveDisplay(entityId);
        }
    }

    // 检查两个位置是否相同
    isSamePosition(pos1, pos2, tolerance = 0.1) {
        return Cesium.Cartesian3.distance(pos1, pos2) < tolerance;
    }

    // 更新primitive显示
    updatePrimitiveDisplay(entityId) {
        const positions = this.pathPositions.get(entityId);
        const polylineCollection = this.pathPrimitives.get(entityId);
        if (!positions || positions.length < 2) {
            polylineCollection.removeAll();
            return;
        }
        // 清空并重新添加（简单更新方式）
        polylineCollection.removeAll();
        polylineCollection.add({
            positions: positions,
            width: 3.0,
            material: Cesium.Material.fromType('Color', {
                color: this.getLineColor(entityId)
            })
        });
    }

    // 获取线条颜色
    getLineColor(entityId) {
        const colors = {
            'default': Cesium.Color.GREEN,
            'usweixing': Cesium.Color.GREEN,
            'enemyweixing': Cesium.Color.GREEN,
            'missileweixing': Cesium.Color.RED
        };
        return colors[entityId] || colors['default'];
    }

    // 手动添加位置点（可选，用于调试）
    manuallyAddPosition(entityId, position) {
        this.addPositionToPath(entityId, position);
    }

    // 获取路径信息
    getPathInfo(entityId) {
        const positions = this.pathPositions.get(entityId);
        return {
            pointCount: positions ? positions.length : 0,
            hasData: positions && positions.length > 0
        };
    }

    // 清理路径
    clearPath(entityId) {
        if (this.pathPositions.has(entityId)) {
            this.pathPositions.set(entityId, []);
            this.updatePrimitiveDisplay(entityId);
        }
    }

    // 移除路径
    removePath(entityId) {
        const polylineCollection = this.pathPrimitives.get(entityId);
        if (polylineCollection) {
            viewer.scene.primitives.remove(polylineCollection);
        }
        this.pathPrimitives.delete(entityId);
        this.pathPositions.delete(entityId);
        this.positionProperties.delete(entityId);
    }
}
